/*
 *  Axolotl - Alternate persistence for Grails
 *  Copyright (C) 2008  Juanjo García Latre
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package com.googlecode.axolotl.jdbc;

import javax.sql.DataSource;

import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.AopContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

import com.googlecode.axolotl.Database;


public abstract class AbstractJdbcDatabase implements Database {

	private PlatformTransactionManager transactionManager;
	private DataSource dataSource;
	private SqlFactory sqlFactory;


	public DataSource getDataSource() {
		return dataSource;
	}


	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.transactionManager = new DataSourceTransactionManager(dataSource);
	}

	
	public SqlFactory getSqlFactory() {
		return sqlFactory;
	}
	
	
	public void setSqlFactory(SqlFactory sqlFactory) {
		this.sqlFactory = sqlFactory;
	}
	

	public TransactionStatus beginTransaction() {
		return transactionManager.getTransaction(null);
	}
	

	public void commit(TransactionStatus status) {
		transactionManager.commit(status);
	}

	
	public void rollback(TransactionStatus status) {
		transactionManager.rollback(status);
	}
	
	
	protected Database getTargetDatabase() {
		try {
			Advised proxy = (Advised) AopContext.currentProxy();
			if (proxy.getTargetSource().getTarget() == this) {
				return (Database) proxy;
			}
		}
		catch (IllegalStateException e) {
		}
		catch (Throwable t) {
			System.out.println("error getting target " + t.getMessage());
		}
		return this;
	}
}
